//https://leetcode.cn/problems/length-of-longest-subarray-with-at-most-k-frequency/
class Solution {
public:
    int maxSubarrayLength(const vector<int>& nums, int k) {
        int left = 0, right = 0;
        unordered_map<int, int> cnt;
        int n = nums.size();
        int maxLength = 0;

        while (right < n) {
            int rightNum = nums[right];
            cnt[rightNum]++;

            while (cnt[rightNum] > k) {
                int leftNum = nums[left];
                cnt[leftNum]--;
                left++;
            }

            maxLength = max(maxLength, right - left + 1);
            right++;
        }

        return maxLength;
    }
};
